'use strict';

// options param : {username, chaincodeId, fcn, args, host, org}
module.exports = async function(options) {
    const Fabric_Client = require('fabric-client');
    const path = require('path');
    const fabric_client = new Fabric_Client();
    try {
        const channel = fabric_client.newChannel('mychannel');
        const peer = fabric_client.newPeer('grpc://' + options.host + ':7051');
        channel.addPeer(peer);
        let member_user = null;
        const store_path = path.join(__dirname, 'hfc-key-store' + options.org);
        console.log('Store path:' + store_path);
        const tx_id = null;
        const state_store = await Fabric_Client.newDefaultKeyValueStore({path: store_path});
        fabric_client.setStateStore(state_store);
        const crypto_suite = Fabric_Client.newCryptoSuite();
        const crypto_store = Fabric_Client.newCryptoKeyStore({
            path: store_path
        });
        crypto_suite.setCryptoKeyStore(crypto_store);
        fabric_client.setCryptoSuite(crypto_suite);
        const user_from_store = await fabric_client.getUserContext(options.username, true);
        if (user_from_store && user_from_store.isEnrolled()) {
            console.log('Successfully loaded ' + options.username + ' from persistence');
            member_user = user_from_store;
        }else {
            console.log('Failed to get ' + options.username + '.... run query.js');
            return;
        }
        const request = {
            chaincodeId: options.chaincodeId,
            fcn: options.fcn,
            args: options.args
        };
        const query_responses = await channel.queryByChaincode(request);
        console.log("Query has completed, checking results");
        if (query_responses && query_responses.length === 1) {
            if (query_responses[0] instanceof Error) {
                console.error("error from query = ", query_responses[0]);
            } else {
                console.log("Response is ", query_responses[0].toString());
                return  query_responses[0].toString()
            }
        } else {
            console.log("No payloads were returned from query");
        }
    } catch (e) {
        console.log(e);
    }
};